package com.jbwz.web.security.util;

import com.jbwz.web.security.entity.Resource;
import com.jbwz.web.security.entity.vo.MenuTreeVO;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class MenuTreeUtil {
    /**
     * 转换菜单数据结构为界面js的tree结构
     */
    public static MenuTreeVO toMenuTreeVO(List<Resource> resourceVOS) {
        Map<String, List<MenuTreeVO>> mapListMenuVO = resourceVOS.parallelStream().map(rv -> {
            MenuTreeVO fvo = new MenuTreeVO();
            fvo.setPid(rv.getParentId().toString());
            fvo.setKey(rv.getId().toString());
            fvo.setTitle(rv.getName());
            return fvo;
        }).collect(Collectors.groupingBy(MenuTreeVO::getPid, Collectors.toList()));
        mapListMenuVO.values().forEach(mtvoList ->
                mtvoList.forEach(mtvo -> {
                    List<MenuTreeVO> children = mapListMenuVO.get(mtvo.getKey());
                    if (Objects.nonNull(children)) {
                        mtvo.setChildren(children);
                    }
                })
        );
        MenuTreeVO menuTreeVO = new MenuTreeVO();
        menuTreeVO.setKey("0");
        menuTreeVO.setTitle("根菜单");
        menuTreeVO.setChildren(mapListMenuVO.get("0"));
        return menuTreeVO;
    }

}
